"use client";

import { useContext, useEffect, useRef, useMemo } from "react";
import { Box, Flex } from "@chakra-ui/react";
import { MainContext } from "@/src/providers/MainProvider";
import Header from "./Common/Header";
import LeftSideBar from "./Common/LeftSideBar";
import MainMouse from "./MainMouse";
import HomePage from "./Common/HomePage";
import { usbDetect } from "../shims/usb-detection";

interface USBDevice extends HIDDevice {
  // 可以在这里添加额外的 USB 设备属性定义
}
interface Parent {
  deviceName?: string;
}
// 声明全局类型
declare global {
  interface Window {
    getBatteryAndWired: () => Promise<{
      battery: number;
      wired: number;
      charge: number;
    }>;
  }
}

interface MainProps {
  showHomePage?: boolean;
  deviceName?: string;
}

const Main = ({ showHomePage = true, deviceName = "" }: MainProps) => {
  const {
    deviceStatus,
    currentTab,
    disconnectMouse,
    connectMouse,
    matchMode,
    battery, // 电量
    chargeFlag, // 充电状态
    connectMode, // 连接模式
    mouseStatus, // 鼠标状态
    connectedMouse,
  } = useContext(MainContext);

  // 使用 useRef 存储状态引用，避免闭包问题
  const refs = {
    deviceStatus: useRef(deviceStatus),
    matchMode: useRef(matchMode),
    // dongleInfo: useRef(dongleInfo),
  };
  const isConnectingRef = useRef(false);

  // 同步更新引用值
  useEffect(() => {
    refs.matchMode.current = matchMode;
  }, [matchMode]);

  useEffect(() => {
    refs.deviceStatus.current = deviceStatus;
  }, [deviceStatus]);

  // USB 设备监听处理
  useEffect(() => {
    // USB 设备移除处理函数
    const handleUSBRemove = () => {
      if (!refs.matchMode.current) {
        disconnectMouse();
        window.history.back();
      }
    };

    // USB 设备连接处理函数
    const handleUSBConnect = () => {
      console.log("handleUSBConnect", refs.matchMode.current);
      connectMouse(
        [{ usagePage: 0xff01, usage: 0x0010 }],
        (window?.parent as Parent).deviceName || ""
      );
    };

    // 启动 USB 监听
    usbDetect.startMonitoring();
    usbDetect.on("remove", handleUSBRemove);
    usbDetect.on("connect", handleUSBConnect);

    // 组件卸载时清理监听器
    return () => {
      usbDetect.off("remove", handleUSBRemove);
      usbDetect.off("connect", handleUSBConnect);
      usbDetect.stopMonitoring();
    };
  }, [connectMouse, disconnectMouse]);

  // 确保只在浏览器环境中执行
  if (typeof window !== "undefined") {
    (window as Window).getBatteryAndWired = async () => {
      console.log(11111, deviceStatus);
      console.log(22222, connectedMouse);
      console.log(33333, battery);
      console.log(44444, connectMode);
      console.log(55555, chargeFlag);
      console.log(66666, mouseStatus);
      if (!deviceStatus || !connectedMouse) {
        return {
          battery: 100,
          // 0 无线 1有线
          wired: 1,
          charge: 0,
          online: 0,
        };
      }
      return {
        battery: battery || 100,
        // 0 无线 1有线
        wired: connectMode === "有线连接" ? 1 : 0,
        charge: chargeFlag ? 1 : 0,
        online: mouseStatus || 0,
      };
    };
  }

  // 从URL加载设备
  useEffect(() => {
    const connectDeviceFromUrl = async () => {
      if (deviceName && !isConnectingRef.current) {
        isConnectingRef.current = true;
        try {
          await connectMouse(
            [{ usagePage: 0xff01, usage: 0x0010 }],
            deviceName
          );
        } finally {
          isConnectingRef.current = false;
        }
      }
    };

    if (deviceName && !deviceStatus) {
      connectDeviceFromUrl();
    }
  }, [connectMouse, deviceName]);

  // 初始连接，只有在没有URL参数时执行
  useEffect(() => {
    if (!deviceName && !isConnectingRef.current) {
      isConnectingRef.current = true;
      try {
        connectMouse(
          [{ usagePage: 0xff01, usage: 0x0010 }],
          (window?.parent as Parent).deviceName || ""
        );
      } finally {
        isConnectingRef.current = false;
      }
    }
  }, [connectMouse, deviceName]);

  const isElectron = useMemo(() => {
    if (typeof navigator !== "undefined") {
      return navigator.userAgent.toLowerCase().indexOf("electron") !== -1;
    } else {
      console.log("运行在服务器端，没有 navigator");
    }
  }, []);

  // 未选择标签页且允许显示首页时，才显示首页
  if (!currentTab && showHomePage) {
    return <HomePage />;
  }

  return deviceStatus ? (
    <Box
      minW="100%"
      minH="100%"
      overflowX="hidden"
      overflowY="hidden"
      bg="#211a31"
      // className="main-bg"
    >
      {/* 顶部导航栏 */}

      <Box as="header" h="60px" w="100%" boxShadow="sm" position="sticky">
        <Header />
      </Box>

      {/* 主要内容区域 */}
      <Flex flex="1">
        {/* 左侧边栏 */}
        <Box as="aside" w="250px" position="sticky" left="0">
          <LeftSideBar />
        </Box>

        {/* 主内容区域 */}
        <Box
          as="main"
          flex="1"
          p={3}
          minW="1030px" // 1280px - 250px(侧边栏宽度)
        >
          <MainMouse />
        </Box>
      </Flex>
    </Box>
  ) : null;
};

export default Main;
